<template>
	<view class="container-battery">
		<text class="battery-percent">剩余容量：{{battery}}%</text>
		<view class="battery-box" @click="touchFun">
			<view class="battery-content" :style="{
					width: widthValue
				}">
				<view class="battery-value" :style="{
						width: batteryValueWidth,
						height: heightValue,
						backgroundImage: batteryColor
					}">
				</view>
			</view>
		</view>
	</view>
</template>
<script>
	function getValue(value) {
		const reg = /(px|rpx)$/;
		const tempValue = value.replace(reg, '');
		return parseInt(tempValue);
	}
	const getUnit = (value) => {
		if (/rpx$/.test(value)) {
			return 'rpx';
		}
		return 'px';
	}

	let timer = null;

	export default {
		props: {
			status: {
				type: Number,
				default: 0
			},
			battery: {
				type: Number,
				default: 0
			},
			showPercent: {
				type: Boolean,
				default: false
			},
			color: {
				type: String,
				default: '#1c1c1c'
			},
			width: {
				type: String,
				default: '22'
			},
			height: {
				type: String,
				default: '12'
			},
			batteryValues: {
				type: Array,
				default: () => {
					return [35, 65, 100]
				}
			},
			batteryColors: {
				type: Array,
				default: () => {
					return ['linear-gradient(45deg, #f43f3b, #ec008c)', 'linear-gradient(45deg, #ff9700, #ed1c24)',
						'linear-gradient(45deg, #0ad4a8, #55f470)'
					]
				}
			}
		},
		computed: {
			widthValue() {
				return getValue(this.width) + getUnit(this.width)
			},
			heightValue() {
				return (getValue(this.height) - 4) + getUnit(this.height)
			},
			batteryValueWidth() {
				return (getValue(this.width) * this.battery) / 100 + getUnit(this.width);
			},
			batteryColor() {
				for (let i = 0; i < this.batteryValues.length; i++) {
					if (this.battery <= this.batteryValues[i]) {
						return this.batteryColors[i]
					}
				}
				return this.batteryColors[this.batteryColors.length - 1]
			},
		},
		methods: {
			touchFun() {
				this.$emit('click')
			}
		}
	}
</script>
<style scoped lang="scss">
	.container-battery {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: space-around;
	}

	.battery-percent {
		font-size: 18px;
		padding: 20rpx;
		font-weight: 900;
	}

	.battery-content {
		border-radius: 24rpx;
		background-color: #FFFFFF;
		border-radius: 24rpx;
		box-shadow: 0rpx 10rpx 12rpx 0rpx #a7a7a7;
		border: 2px solid #ffffff;
		display: flex;
		flex-direction: row;
	}

	.battery-box {
		position: relative;
		padding-right: 4px;
	}

	.battery-value {
		border-radius: 20rpx;
		height: 8px;
		overflow: hidden;
	}
</style>